"use strict";

const Controller = require("egg").Controller;
const jwt = require("jsonwebtoken");
const Mock = require("mockjs");

let checkCode = null;

class LoginController extends Controller {
    // 验证码
    async createCode() {
        const { ctx } = this;
        // 生成随机6位数                <最小 (区间)  最大>
        checkCode = Mock.mock("@natural(100000, 999999)");
        ctx.body = {
            code: 200,
            msg: "请求成功",
            checkCode,
        };
    }

    // 登录
    async login() {
        const { ctx, app } = this;
        const { phone, code } = ctx.request.body;
        if (code * 1 !== checkCode * 1) {
            ctx.body = {
                code: "000",
                msg: "验证码错误",
            };
        }
        const data = await app.mysql.get("login", { phone });
        if (data) {
            // 返回自定义网络响应码
            // ctx.response.status = 500;
            ctx.body = {
                code: "200",
                msg: "登录成功",
                token: jwt.sign(data.phone, "sx"),
            };
        } else {
            // 生成随机图片
            const img = Mock.mock("https://unsplash.it/57/57/?@name");

            //生成随机名字;
            const name = Mock.mock("@cname");
            await app.mysql.insert("login", { phone, img, name });
            const data = await app.mysql.get("login", { phone });

            ctx.body = {
                code: "200",
                msg: "注册成功",
                token: jwt.sign(data.phone, "sx"),
            };
        }
    }
}

module.exports = LoginController;